﻿#define _CRT_SECURE_NO_WARNINGS 1
#include"LTNode.h"

//初始化----创建头节点
LTNode* Init()
{
	LTNode* phead = (LTNode*)malloc(sizeof(LTNode));
	phead->data = -1;
	phead->next = phead->prev = phead;
	return phead;
}


//打印
void LTNPrint(LTNode* phead)
{
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		printf("%d -> ", pcur->data);
		pcur = pcur->next;
	}
	printf("\n");
}
//创建新节点
LTNode* NodeBuy(LTDataType x)
{
	LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		exit(1);
	}
	newnode->data = x;
	newnode->next = newnode->prev = newnode;
	return newnode;
}
//尾插
void LTNPushBack(LTNode* phead, LTDataType x) 
{
	assert(phead);
	LTNode* node = NodeBuy(x);
	node->next = phead;
	node->prev = phead->prev;

	phead->prev->next = node;
	phead->prev = node;
}

//头插
void LTNpushFront(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* node = NodeBuy(x);
	node->prev = phead;
	node->next = phead->next;

	phead->next = node;
	phead->next->prev = node;
}

//尾删
void LTNPopBack(LTNode* phead)
{
	assert(phead->next != phead);
	LTNode* pcur = phead->prev;
	phead->prev = pcur->prev;
	pcur->prev->next = phead;

	free(pcur);
	pcur = NULL;
}

//头删
void LTNPopFront(LTNode* phead)
{
	assert(phead->next != phead);
	LTNode* pcur = phead->next;
	pcur->next->prev = phead;
	phead->next = pcur->next;

	free(pcur);
	pcur = NULL;
}

//查找
LTNode* LTFind(LTNode* phead, LTDataType x)
{
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		if (pcur->data == x)
			return pcur;
		pcur = pcur->next;
	}
	return NULL;
}

//在pos位置之后插⼊数据
void LTInsert(LTNode* pos, LTDataType x)
{
	assert(pos);
	LTNode* pcur = pos->next;
	LTNode* node = NodeBuy(x);
	pos->next = node;
	node->prev = pos;
	node->next = pcur;
	pcur->prev = node;
}

//在pos位置删除数据
void LTErase(LTNode* pos)
{
	assert(pos);
	pos->prev->next = pos->next;
	pos->next->prev = pos->prev;

	free(pos);
	pos = NULL;
}

//销毁
void LTDestroy(LTNode** pphead)
{
	LTNode* pcur = (*pphead)->next;
	while (pcur != *pphead)
	{
		LTNode* ptail = pcur->next;
		free(pcur);
		pcur = ptail;
	}
	//释放头节点
	free(*pphead);
	*pphead = NULL;
}